package com.ruipengkj.bar;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;

import com.ruipengkj.init.InitContext;
public class CheckUpdate extends  JFrame {
	class FileInfo 
	{
		int size;
		String url;
		
		
		public FileInfo(int size, String url) {
			super();
			this.size = size;
			this.url = url;
		}
		public int getSize() {
			return size;
		}
		public void setSize(int size) {
			this.size = size;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		
		
	}
	
	JLabel msg = new JLabel("正在查找网络上的更新资源... ");
    JProgressBar probar = new JProgressBar(0,200);
//    JButton OKButton = new JButton("OK");
//	JFrame c = this; 
	public CheckUpdate(){
		//设置窗体属性
		setAttb();
	Container con = this.getContentPane();
	con.setLayout(new FlowLayout());   
//    OKButton.addActionListener(this);
//	OKButton.setEnabled(false);
    
    con.add(msg);
    con.add(probar);
//    con.add(OKButton);
   
    //启动更新线程
    new Check(msg,probar).start();
    
	}
	
	private class Check extends Thread {
	
	private static final String ServiceURL = "http://www.dlwoo.com";
//	private static final String ServiceURL = "http://localhost:8080/Update";
	
	double sum = 0;
	double sums = 0;
	double s = 0;
    //标识,是否存在新的更新文件
    private boolean isUpdated = false;
    //保存新的版本
    String netVersion;
    //保存要更新的文件名称
    ArrayList netList = new ArrayList(); 
    //保存要更新的文件路径
    ArrayList netPathList = new ArrayList();
    //保存要更新的文件的版本号                                         此版本号为对应版本文件在服务器上所对应的文件夹
    ArrayList netVerList = new ArrayList();
    //保存要更新的文件的大小
    ArrayList netSizeList = new ArrayList();
    //本地版本文件
    //String LocalVerFileName  =  "ver.txt";

    //显示信息
    private JProgressBar probar;
    private JLabel msg;
    private JLabel process;
//    private JButton OKButton;

    public Check(JLabel msg, JProgressBar probar) {
      this.msg = msg;
      this.probar = probar;
//      this.OKButton = OKButton;
    }
    
    public void run() {
    //更新文件版本标识URL
    String versionUrl = ServiceURL+"/"+"Version";

    URL url = null;
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader netVer = null;

    //读取网络上的版本
    try {
    	 url = new URL(versionUrl);
         is = url.openStream();
         isr = new InputStreamReader(is);

         netVer = new BufferedReader(isr);
         double netVerStr = 0;
         double newVer = 0;
        
         String verStr = getNowVer();
         double localVerStr = Double.parseDouble(verStr);
         
         String str = "";
         
         while((str = netVer.readLine()) != null)
         {
         	String[] strs = str.split(",");
         	netVerStr = Double.parseDouble(strs[0]);
         	if(netVerStr>newVer){
         		newVer = netVerStr;
         	}
         	if(localVerStr<netVerStr){
         		String pathStr = strs[1];
             	int splitIndex = pathStr.lastIndexOf("/");
             	if(splitIndex<0){
             		netVerList.add(String.valueOf(netVerStr).trim());
             		netPathList.add("");
             		netList.add(strs[1]);
             		netSizeList.add(strs[2]);
             		sum += Double.valueOf(strs[2]);
             	}else{
             		netVerList.add(String.valueOf(netVerStr).trim());
             		netPathList.add(pathStr.substring(0, splitIndex).trim());
             		netList.add(pathStr.substring(splitIndex+1));
             		netSizeList.add(strs[2]);
             		sum += Double.valueOf(strs[2]);
             	}
             	
         	}
         }
        

         if (newVer==localVerStr) {
           msg.setText( "当前文件是最新版本\n ");
           isUpdated = false;
         } else {
           msg.setText( "存在更新文件,正在更新...\n ");
           isUpdated = true;
           netVersion = String.valueOf(newVer);
         }

    } catch (MalformedURLException ex) {
//    	JOptionPane
//		.showMessageDialog(null, "服务器地址错误！");
    	dispose();
    } catch (IOException ex) {
//    	JOptionPane
//		.showMessageDialog(null, "未连接服务器！");
    	dispose();
    } finally {
        //释放资源
        try {
        	if(netVer!=null){
        		netVer.close();
        	}
        	if(isr!=null){
        		isr.close();
        	}if(is!=null){
        		is.close();
        	}
        } catch (IOException ex1) {
        	dispose();
        }
    } 
    
    
     
    //如果版本不同,下载网络上的文件,更新本地文件
    String programName = "";
    if (isUpdated) {    	
    	try{
    	for(int i = netList.size();i > 0; i--){
        	
        	programName = netList.get(i-1).toString();
        	this.mkdir("temps");
        	//本地要被更新的文件
            File oldFile = new File("temps/"+ programName);
            //缓存网络上下载的文件
            File newFile = new File("temp");
           
            //网络上的文件位置
            String updateUrl =ServiceURL + "/" + netVerList.get(i-1) + "/" + programName;
          
            HttpURLConnection httpUrl = null;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;

            try {
              //打开URL通道
              url = new URL(updateUrl);
              httpUrl = (HttpURLConnection) url.openConnection();

              httpUrl.connect();

              byte[] buffer = new byte[1024*10];

              int size = 0;

              is = httpUrl.getInputStream();
              bis = new BufferedInputStream(is);
              fos = new FileOutputStream(newFile);

              msg.setText( "正在从网络上下载新的更新文件\n ");

              //保存文件
                while ((size = bis.read(buffer)) != -1) {
                    //读取并刷新临时保存文件
                    fos.write(buffer, 0, size);
                    fos.flush();
                    s += size;
                    sums = (int) (200*s/sum);
                    probar.setValue((int) sums);
                }

              
//                sum += this.getFileSize(newFile);

              //把下载的临时文件替换原有文件
              CopyFile(oldFile,newFile);
             
//              s = this.getFileSize(newFile);
              
              
              
          	  
              

            }   finally {
              try {
            	if(fos!=null){
            		  fos.close();
            	}
                if(bis!=null){
                	bis.close();
                }
                if(is!=null){
                	is.close();
                }
                httpUrl.disconnect();
              } catch (IOException ex3) {
            	  ex3.printStackTrace();
            	  dispose();
              }
            }
        }

    	
    	
        for(int i = 0; i < netList.size();i++){
        	
        	msg.setText( "\n文件下载完成,正在更新...\n ");
        	
        	programName = netList.get(i).toString();
        	this.mkdir((String) netPathList.get(i));
        	//本地要被更新的文件
            File oldFile = new File(netPathList.get(i)+"/"+programName);
            //缓存网络上下载的文件
            File newFile = new File( "temps/"+programName);
            
//            double s = this.getFileSize(newFile);

           
            
            
        	CopyFile(oldFile,newFile);        	
        }
        
		//把本地版本文件更新为网络同步
		
	        try {
				UpdateLocalVerFile();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        System.exit(0);        
    	}
    	catch (MalformedURLException ex2) {
//        	msg.setText("未成功连接至服务器");
//        	JOptionPane
//			.showMessageDialog(null, "未成功连接至服务器！");
    		
        	dispose();
        } catch (IOException ex) {
//          msg.setText( "文件读取错误\n ");
//        	JOptionPane
//			.showMessageDialog(null, "文件读取错误");
          dispose();
        }catch (Exception e) {
        	
		}        
    }
	
    //退出更新程序
    dispose();
  } 
    
  //复制文件
    private void CopyFile(File oldFile, File newFile) throws IOException {
      FileInputStream in = null;
      FileOutputStream out = null;
      try {
        if(oldFile.exists()){
            oldFile.delete();
        }
        in = new FileInputStream(newFile);
        out = new FileOutputStream(oldFile);
        
        byte[] buffer = new byte[1024 * 5];
        int size;
        while ((size = in.read(buffer)) != -1) {
            out.write(buffer, 0, size);
            out.flush();
        }
      }  finally {
        try {
        	if(out!=null){
        		out.close();
        	}
            if(in!=null){
            	in.close();
            }
        } catch (IOException ex1) {
        	dispose();
        }
      }

    }

    private void UpdateLocalVerFile() throws FileNotFoundException, IOException {
    	Properties ps = InitContext.getinstance().LoadDataBaseData();
    	ps.setProperty("pool.LocalVer", netVersion);
    	ps.store(new FileOutputStream("jdbc.properties"), "");
//      //把本地版本文件更新为网络同步
//      FileWriter verOS = null;
//      BufferedWriter bw = null;
//      try {
//        verOS = new FileWriter(LocalVerFileName);
//
//        bw = new BufferedWriter(verOS);
//        bw.write(netVersion);
//        bw.flush();
//
//      } catch (IOException ex) {
////    	  JOptionPane
////			.showMessageDialog(null, "版本文件读取错误！");
//    	  dispose();
//      } finally {
//        try {
//        	if(bw!=null){
//        		bw.close();
//        	}
//            if(verOS!=null){
//            	verOS.close();
//            }
//        } catch (IOException ex1) {
////        	JOptionPane
////			.showMessageDialog(null, "关闭文件流错误！");
//        	dispose();
//        }
//      }
    }
    
    private double getFileSize(File f) throws Exception{
    	double s = 0;
    	if(f.exists()){
    		FileInputStream fis = new FileInputStream(f);
    		s = fis.available();//单位为K
    		fis.close();
    	}
    	return s;
    }
    
    // 创建文件路径  
    public void mkdir(String path) {  
    	File fd = new File(path);  
        if (!fd.exists()) {  
            fd.mkdirs();  
        }  
    }  

    private String getNowVer() {
    	
    	Properties ps = InitContext.getinstance().LoadDataBaseData();
        String str =  ps.getProperty("pool.LocalVer");
    	
        if(!(str==null || str.equals(""))){
        	return str;
        }
//      //本地版本文件
//      File verFile = new File(LocalVerFileName);
//
//      FileReader is = null;
//      BufferedReader br = null;
//
//      //读取本地版本
//      try {
//      	if(verFile.exists())
//      	{
//        is = new FileReader(verFile);
//
//        br = new BufferedReader(is);
//        String ver = br.readLine();
//
//        return ver;
//      	}
//      } catch (FileNotFoundException ex) {
//    	  String ver = "0";
//    	  return ver;
//      } catch (IOException ex) {
////    	  JOptionPane
////			.showMessageDialog(null, "版本文件读取异常！");
//    	  dispose();
//      } finally {
//        //释放资源
//        try {
//            if(br != null)br.close();
//            if(is != null)is.close();
//        } catch (IOException ex1) {
//        }
//      }
      return "0";
    }
}


private void setAttb() {
    //窗体设置
    this.setTitle( "Auto Update ");
    this.setSize(400, 300);
    this.setLayout(new BorderLayout());
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    // 窗体居中
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = this.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    this.setLocation((screenSize.width - frameSize.width) / 2,
              (screenSize.height - frameSize.height) / 2);
}

	private void doShutDownWork() {  
		final Runtime run=Runtime.getRuntime();//当前 Java 应用程序相关的运行时对象。  
		run.addShutdownHook(new Thread(){ //注册新的虚拟机来关闭钩子  
			@Override  
			public void run() {  
				try {
//					run.exec("C:\\Program Files\\店联网进销存\\店联进销存.exe", null, new File("C:\\Program Files\\店联网进销存"));
					run.exec("店联进销存.exe");
				} catch (IOException e) {
					JOptionPane
					.showMessageDialog(null, "未找到指定程序！");
					dispose();
				}
			}  
		});  
	}  

	public static void main(String[] args) {
	    CheckUpdate checkupdate = new CheckUpdate();
	    checkupdate.doShutDownWork();  
	   
	    checkupdate.setVisible(true);
	}

} 
